package config.java;

import java.io.File;

public abstract class FileWatchDog extends Thread {

	/**
	 * The name of the file to observe for changes.
	 */
	protected String filename;

	protected String alias = "defAlias";
	
	private ConfigValue value = ConfigValue.getInstance();
	
	/**
	 * The delay to observe between every check. By default set {@link
	 * #DEFAULT_DELAY}.
	 */
	protected long delay = 60 * 1000;

	File file;
	long lastModif = 0;
	boolean warnedAlready = false;
	boolean interrupted = false;

	protected FileWatchDog(String filename,String alias,long delay) {
		this.filename = filename;
		this.alias = alias;
		this.delay = delay;
		if(this.delay < 1000)          //监测时长不能小于1秒
			this.delay = 1000;
		file = new File(filename);
		setDaemon(true);
		try{
			checkAndConfigure();
		}catch(Exception ex){
			
		}
	}

	/**
	 * Set the delay to observe between each check of the file changes.
	 */
	public void setDelay(long delay) {
		this.delay = delay;
	}

	abstract protected void parseOnChange();

	protected void checkAndConfigure() throws Exception{
		boolean fileExists;
		ConfigBin bin = value.getConfBin(alias);
		try {
			fileExists = file.exists();
		} catch (SecurityException e) {
			ConfigLog.errorLog("Was not allowed to read check file existance, file:["
					+ filename + "].");
			interrupted = true; // there is no point in continuing
			if(bin != null){
				bin.setLoadTime(System.currentTimeMillis());
				bin.setStatus(-1);
				bin.setError("File was not allowed to read check file existance");
			}
			return;
		}

		if (fileExists) {
			long l = file.lastModified(); // this can also throw a
											// SecurityException
			boolean bl = (bin == null ? true : bin.getStatus() != 1);
			if (l > lastModif || bl) { // however, if we reached this point this
				lastModif = l; // is very unlikely.
				parseOnChange();
				warnedAlready = false;
			}
		} else {
			if (!warnedAlready) {
				ConfigLog.errorLog("load config file failed! [" + filename + "] does not exist.");
				warnedAlready = true;
				if(bin != null){
					bin.setLoadTime(System.currentTimeMillis());
					bin.setStatus(-1);
					bin.setError("File does not exist");
				}
			}
		}
	}

	public void run() {
		boolean b = true;
		while (b) {
			try {
				Thread.currentThread().sleep(delay);
				checkAndConfigure();
			} catch (Exception e) {
				// no interruption expected
			}
			
		}
	}
}
